package com.gzhryc.shared_device.iot.core;

import com.gzhryc.common.logging.Logger;
import org.apache.poi.ss.formula.functions.T;

import java.util.concurrent.*;

/**
 * IOT工作线程
 * @author zhanghao
 *
 */
public class IOTWorkThreadFactory {
	
	static Logger log = Logger.getLogger(IOTWorkThreadFactory.class);
	
	static IOTWorkThreadFactory self;
	
	public static IOTWorkThreadFactory get() {
		if(self == null) {
			self = new IOTWorkThreadFactory();
		}
		return self;
	}
	
	ThreadPoolExecutor executorService;

	public IOTWorkThreadFactory() {
		if(executorService != null) {
			executorService.shutdown();
			executorService = null;
		}
		int poolSize = Runtime.getRuntime().availableProcessors();
		BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(32);
		RejectedExecutionHandler policy = new ThreadPoolExecutor.DiscardOldestPolicy();
		executorService = new ThreadPoolExecutor(poolSize * 5, poolSize * 10, 180, TimeUnit.SECONDS,queue,policy);
	}
	
	public void execute(Runnable runnable) {
		executorService.execute(runnable);
		if(executorService.getQueue().size() > 30) {
			log.info("核心线程数：" + executorService.getCorePoolSize());
			log.info("存活线程数：" + executorService.getActiveCount());
			log.info("已执行的任务数：" + executorService.getTaskCount());
			log.info("已完成的任务数：" + executorService.getCompletedTaskCount());
			log.info("队列任务数：" + executorService.getQueue().size());
		}
	}
	
	public Future<T> submit(Callable<T> task) {
		return executorService.submit(task);
	}
}
